import jsonAPI from 'json-server';
import  { resolve } from 'path';
import fetch from 'isomorphic-fetch'
import config from 'config';
import {Message, MessageType, Office, Supplies, SuppliesOrder, User} from "./models";

export default () => {
  const server = jsonAPI.create(); // 创建一个 express 服务
  server.use(jsonAPI.defaults()); // 默认中间件
  server.use(jsonAPI.bodyParser); // json 服务

  server.post('/users',(req,res,next) => {
    try {
      req.body = new User(req.body);
    }catch (e) {
      return res.status(400).json({error: 400 , message: e.message})
    }
    return next();
  });
  server.post("/messages",async (req,res,next) => {
    try {
      req.body = new Message(req.body);
    }catch (e) {
      return res.status(400).json({error: 400 , message: e.message})
    }
    req.body.user = await fetch(`${config.get('ENDPOINT')}/users/${req.body.userId}`,{
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(res => res.json())
    return next();
  })
  server.post("/MessageTypes",(req,res,next) => {
    try {
      req.body = new MessageType(req.body);
    }catch (e) {
      return res.status(400).json({error: 400 , message: e.message})
    }
    return next();
  })
  server.post("/offices",async (req,res,next) => {
    try {
      req.body = new Office(req.body);
    }catch (e) {
      return res.status(400).json({error: 400 , message: e.message})
    }
    req.body.user = await fetch(`${config.get('ENDPOINT')}/users/${req.body.userId}`,{
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(res => res.json())
    return next();
  })

  server.post("/supplies",(req,res,next) => {
    try {
      req.body = new Supplies(req.body);
    }catch (e) {
      return res.status(400).json({error: 400 , message: e.message})
    }
    return next();
  })
  server.post("/suppliesOrders",async (req,res,next) => {
    try {
      req.body = new SuppliesOrder(req.body);
    }catch (e) {
      return res.status(400).json({error: 400 , message: e.message})
    }

    // 借出 工资的时候，我们需要核实下 具体物资是否充足
    let supplies = await fetch(`${config.get('ENDPOINT')}/supplies/${req.body.suppliesId}`,{
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(res => res.json());
    if (supplies.total - supplies.borrowTotal - (+req.body.quantity) < 0){
      return res.status(500).json({message: '借出数量不足'});
    }
    fetch(`${config.get('ENDPOINT')}/supplies/${req.body.suppliesId}`,{
      method: 'PATCH',
      body: JSON.stringify({borrowTotal: supplies.borrowTotal + (+req.body.quantity)}),
      headers: {
        'Content-Type': 'application/json'
      }
    });
    return next();
  })

  server.use(jsonAPI.router(resolve(__dirname,'..','db','db.json')));
  return server;

}
